import { computed, onMounted, onUnmounted } from 'vue';
import { useStore } from 'vuex';
import { onBeforeRouteLeave, useRoute } from 'vue-router';
import { GlobalDataProps } from '../store/index';
import { Modal } from 'ant-design-vue';

// 在Editor 中完成保存作品一系列的相关的功能
function useSaveWork(disableSideEffects = false) {
  // 数据准备
  const route = useRoute();
  const currentWorkId = route.params.id;
  const store = useStore<GlobalDataProps>();
  const saveIsLoading = computed(() => store.getters.isOpLoading('saveWork'));
  const components = computed(() => store.state.editor.components);
  const page = computed(() => store.state.editor.page);
  const isDirty = computed(() => store.state.editor.isDirty);
  // 1.保存函数
  const saveWork = () => {
    const { title, props, coverImg } = page.value;
    const payload = {
      title,
      coverImg,
      content: {
        components: components.value,
        props,
      },
    };
    store.dispatch('saveWork', {
      data: payload,
      urlParams: { id: currentWorkId },
    });
  };
  // 2.自动保存
  if (!disableSideEffects) {
    let timer: NodeJS.Timer
    onMounted(() => {
      timer = setInterval(() => {
        if (isDirty.value) {
          saveWork();
        }
      }, 1000 * 50);
    });
    onUnmounted(() => {
      clearInterval(timer);
    });
    // 3. 保存前离开路由前的一个提示
    onBeforeRouteLeave((to, from, next) => {
      if (isDirty.value) {
        Modal.confirm({
          title: '作品还未保存，是否保存?',
          okText: '保存',
          okType: 'primary',
          cancelText: '不保存',
          onOk: async () => {
            await saveWork();
            next();
          },
          onCancel: () => {
            next();
          },
        });
      } else {
        next();
      }
    });
  }
  return {
    saveWork,
    saveIsLoading,
  };
}

export default useSaveWork;
